﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acme.TestSite.Objects;
using Acme.Northwind.EFDAL.Entity;
using Acme.Northwind.EFDAL;

namespace Acme.TestSite
{
	public partial class SupplierItem : BasePersistablePage
	{
		#region Page Events

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			cmdSave.Click += new EventHandler(SaveData);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
		}

		#endregion

		#region Methods

		protected override nHydrate.EFCore.DataAccess.NHEntityObject CreateObject(NorthwindEntities context)
		{
			var newItem = new Acme.Northwind.EFDAL.Entity.Supplier();
			context.AddItem(newItem);
			return newItem;
		}

		protected override void SetupBindings(NorthwindEntities context)
		{
			var supplierId = this.Request["id"].ToInt32();
			var supplier = context.Supplier.FirstOrDefault(x => x.UserId == supplierId);
			if (supplier == null)
				supplier = CreateObject(context) as Acme.Northwind.EFDAL.Entity.Supplier;

			Mapper.Map(lblSupplierId, supplier, Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.UserId);
			Mapper.Map(txtAddress, supplier, Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.Address, lblAddress);
			Mapper.Map(txtCity, supplier, Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.City, lblCity);
			Mapper.Map(txtCompany, supplier, Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.CompanyName, lblCompany);
			Mapper.Map(txtContact, supplier, Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.ContactTitle, lblContact);
			Mapper.Map(txtHomePage, supplier, Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.HomePage, lblHomePage);
			Mapper.Map(txtPhone, supplier, Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.Phone, lblPhone);
			Mapper.Map(txtZip, supplier, Acme.Northwind.EFDAL.Entity.Supplier.FieldNameConstants.PostalCode, lblZip);
		}

		#endregion

		#region Event Handlers

		private void cmdCancel_Click(object sender, EventArgs e)
		{
			this.Response.Redirect(SessionHelper.LastSupplierListSearch);
		}

		protected override void OnDataSavedSucess(EventArgs e)
		{
			base.OnDataSavedSucess(e);
			this.Response.Redirect(SessionHelper.LastSupplierListSearch);
		}

		#endregion

	}
}